package edu.nuist.shixun.api.product;

import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import edu.nuist.shixun.excel.excel;
import edu.nuist.shixun.excel.ExcelReader ;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@CrossOrigin
@RestController
public class ExcelUploadAPI {
    @PostMapping("/excel/upload")
    public Object receive(MultipartFile file) {
        Map map = new HashMap();
        String filename = file.getOriginalFilename();
        log.info("接收到一个excel文件:" + filename);
        log.info("创建一个解析excel文件的监听器");
        ExcelReader listener = new ExcelReader();
        try {
            log.info("开始解析excel文件");
            EasyExcel.read(file.getInputStream(), ExcelReader.class, listener)
                    .sheet().doRead();
            log.info("excel文件解析成功");
            log.info("从监听器中取出解析出来的数据");
            List<excel> list = listener.getList();
            log.info("打印数据看一下");
            System.out.println(list);
            map.put("code", "1");
            map.put("message", "excel文件导入成功");
            map.put("data", list);
            return map;
        } catch (IOException e) {
            log.error("发送解析异常");
            map.put("code", "-1");
            map.put("message", "excel文件解析失败,请检查文件格式");
            return map;
        }
    }
}

